home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 7998 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: ccshst05.cs.uoguelph.ca!ccshst01!thay
  2. From: thay@uoguelph.ca (Toby K Hay)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Counting high bits  (was (no subject))
  5. Date: 29 Feb 1996 23:07:03 GMT
  6. Organization: University of Guelph
  7. Message-ID: <4h5bin$i2t@ccshst05.cs.uoguelph.ca>
  8. References: <4gv493$p09@nuacht.iol.ie>
  9. NNTP-Posting-Host: ccshst01.cs.uoguelph.ca
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. Roy Leonard (rleonard@ferrotec.ie) wrote:
  13. : I have a strange problem from an embedded system.  I have an array of 
  14. : data, and
  15. : I want to count all the high bits (=1) in the array.
  16. : The data is of fixed length (roughly 50 long ints).  Each bit is evenly
  17. : weighted.
  18. : Eg.
  19. : If the data in binary was "1001001", the total I'm looking for is three.
  20.  
  21. I'm doing this too in a program.  My solution was the following routine:
  22.  
  23. #define INTLENGTH = 16             /* Integer length is 16 bits */
  24.  
  25. int CountOnes(int SourceInt)
  26. /* Count the high bits in the integer SourceInt. */
  27. {
  28.    int i,NumOnes;                  /* loop index and accumulator        */
  29.    NumOnes = 0;                    /* initialize accumulator            */ 
  30.    for (i=0;i<INTLENGTH;i++)       /* for each bit of the integer . . . */
  31.       {
  32.       NumOnes += (1 & SourceInt); /* increment NumOnes if int ends in 1 */
  33.       SourceInt = SourceInt >> 1; /* shift int 1 to the right           */
  34.       }
  35.    return NumOnes;                /* NumOnes = number of high bits      */
  36. }
  37.  
  38. I'd be glad to hear from more experienced programmers who know of faster 
  39. ways of doing this. 
  40. Toby Hay    thay@uoguelph.ca
  41.